package com.teacher.hong.servlet.student;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.teacher.hong.bean.Page;
import com.teacher.hong.entity.Student;
import com.teacher.hong.service.IClazzService;
import com.teacher.hong.service.IStudentService;
import com.teacher.hong.service.impl.ClazzServiceImpl;
import com.teacher.hong.service.impl.StudentServiceImpl;
import com.teacher.hong.utils.TokenUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 学生分页列表接口
 */
//@WebServlet("/students")
public class StudentServlet extends HttpServlet {

    IStudentService studentService;
    IClazzService clazzService;

    @Override
    public void init() throws ServletException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        studentService = context.getBean("studentService", StudentServiceImpl.class);
        clazzService = context.getBean("clazzService", ClazzServiceImpl.class);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int pageIndex = req.getParameter("pageIndex") == null ? 1 : Integer.parseInt(req.getParameter("pageIndex")); //当前页码
        Integer clazzId = Integer.parseInt(req.getParameter("clazzId"));
        String name = req.getParameter("name");
        Page<Student> studentPage = studentService.page(pageIndex, clazzId, name);

        JSONObject object = new JSONObject(true);
        object.put("state", 200);

        object.put("value", JSON.toJSON(studentPage));
        object.put("timestamp", LocalDateTime.now());

        resp.setStatus(200);

        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(object.toJSONString());
    }
}
